package com.cuixichang.minimalism.basal.utils;

import java.util.Comparator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TreeUtil {
    public static <T> List<T> streamToTree(List<T> treeList, Object parentId , Function<T, Object> pointIdFunction,
                                           Function<T, Object> pointParentIdFunction, BiConsumer<T,List<T>> pointSetSubsetsFunction,
                                           Comparator<? super T> comparator) {
        return streamToTree2(treeList,treeNode -> treeNode,parentId,pointIdFunction,pointParentIdFunction,pointSetSubsetsFunction,comparator);
    }

    public static <T,R> List<R> streamToTree2(List<T> treeList,Function<T, R> transitionFunction, Object parentId , Function<R, Object> pointIdFunction,
                                           Function<R, Object> pointParentIdFunction, BiConsumer<R,List<R>> pointSetSubsetsFunction,
                                           Comparator<? super R> comparator) {
        return treeList.stream().map(child -> transitionFunction.apply(child))
                // 过滤父节点
                .filter(parent -> pointParentIdFunction.apply(parent).equals(parentId))
                // 把父节点children递归赋值成为子节点
                .map(child -> {
                    pointSetSubsetsFunction.accept(child,streamToTree2(treeList,transitionFunction,pointIdFunction.apply(child),
                            pointIdFunction,pointParentIdFunction,pointSetSubsetsFunction,comparator));
                    return child;
                }).sorted(comparator).collect(Collectors.toList());
    }
}
